package com.fc.test.service;

import com.fc.test.common.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Service
public class FileService {
    private final Path filePath= Paths.get("/data/tmp/").toAbsolutePath().normalize();

    public AjaxResult upload(MultipartFile uploadFile){
            String filePath="/data/tmp/";
            String filename=uploadFile.getOriginalFilename();
            filename=filename.hashCode()+filename.substring(filename.lastIndexOf("."));
            File dest=new File(filePath+filename);
        try {
            uploadFile.transferTo(dest);
            log.info(filename+" 上传成功");
            return AjaxResult.success(filename);
        } catch (IOException e) {
            e.printStackTrace();

        }
        return AjaxResult.error("上传失败");
    }

    public Resource loadFileAsResource(String fileName) throws Exception {
        try {
            Path filePath = this.filePath.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new Exception("File not found " + fileName);
            }
        } catch ( MalformedURLException ex) {
            throw new Exception("File not found " + fileName, ex);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
